import logging

from aiogram import Bot
from fluentogram import TranslatorRunner

from src.application.order.enums import OrderType, ReloadType
from src.application.order.service import OrderService
from src.presentation.tg_bot.services.tg_helpers import send_tg_message
from src.presentation.tg_bot.worker.exception_handler import exception_handler

logger = logging.getLogger(__name__)


@exception_handler
async def update_rotation_type(
    ctx,
    locale: TranslatorRunner,
    user_id: int,
    order_id: int,
    rotation_period: int,
    reload_type: ReloadType,
) -> None:
    """Изменяем тип ротации для прокси из заказа"""

    bot: Bot = ctx["bot"]
    order_service: OrderService = ctx["order_service"]

    order = await order_service.get_order_by_id(order_id)
    if await order_service.update_rotation_type(order_id):  # TODO Это должно быть в server_service:
        # server_proxies = await get_server_proxies(session, order.proxies)
        #
        # for server, proxies in server_proxies.items():
        #     await change_rotation_type(server, proxies, rotation_period, reload_type)
        #
        # await update_rotation_period(session, order.proxies, rotation_period, reload_type)

        if order.order_type == OrderType.subscription:
            msg = locale.get("subscription-rotation-change-success")
        else:
            msg = locale.get("rotation-change-success", order_id=str(order.id))
        await send_tg_message(bot, user_id, msg)

        # logger.info(f"Изменена ротация заказа/подписки №{order.id}")
    else:
        # except Exception as e:
        #     logger.exception(e)
        if order.order_type == OrderType.subscription:
            msg = locale.get("subscription-change-rotation-error")
        else:
            msg = locale.get("change-rotation-error", order_id=str(order.id))
        await send_tg_message(bot, user_id, msg)
